package com.network;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.List;

import static com.network.NetConstantsKt.*;

public class HeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl oldHttpUrl = request.url();
        Request.Builder builder = request.newBuilder();
        List<String> headerValues = request.headers(URL_NAME);

//        String mUserInfo = SPUtils.getStringValue(BaseApplication.context, SPUtils.KEY_USER_INFO, "");
//        if (mUserInfo != null && !mUserInfo.equals("")) {
//            builder.addHeader("s", new Gson().fromJson(mUserInfo, LoginBean.class).getSessionID());
//        }

        if (headerValues != null && headerValues.size() > 0) {
            builder.removeHeader(URL_NAME);
            String headerValue = headerValues.get(0);
            HttpUrl newBaseUrl = null;
            if (URL_INFO_VALUE.equals(headerValue)) {
                newBaseUrl = HttpUrl.parse(URL_INFO);
            } else {
                newBaseUrl = oldHttpUrl;
            }
            HttpUrl newFullUrl = oldHttpUrl
                    .newBuilder()
                    .scheme(newBaseUrl.scheme())
                    .host(newBaseUrl.host())
                    .port(newBaseUrl.port())
                    .build();
            return chain.proceed(builder.url(newFullUrl).build());
        }
        return chain.proceed(request);
    }
}